package com.ruoyi.framework.mqtt.handler;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.project.instrument.domain.InsReagent;
import com.ruoyi.project.instrument.service.IInsReagentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author Taney
 */
@Component
public class ReagentUseHandler extends AbstractHandler {

    public static final String TOPIC = "/event/reagentUse";
    /**
     * 试剂已使用标记
     */
    public static final String USE_FLAG = "1";

    @Resource
    IInsReagentService reagentService;

    @Override
    public void handleMessage(Message message, String topic, String msg) throws MessagingException {
        if (matches(TOPIC, topic)) {
            ClientInfo clientInfo = getClientInfo(topic);
            String product = clientInfo.getProduct();
            String deviceId = clientInfo.getDeviceId();
            logger.debug("设备[{}-{}]试剂使用，条码为【{}】", product, deviceId, msg);
            if (msg != null) {
                String[] arr = msg.split(",");
                List<String> barcodes = Arrays.asList(arr);
                InsReagent reagent = new InsReagent();
                //1.标记试剂为已使用2.今日试剂使用数量+1（todo 需要在更换试剂时上报某个试剂已使用完）
                barcodes.forEach(barcode -> {
                    UpdateWrapper<InsReagent> insReagentUpdateWrapper = new UpdateWrapper<>();
                    insReagentUpdateWrapper.eq("barcode", barcode);
                    reagent.setUseFlag(USE_FLAG);
                    reagentService.update(reagent, insReagentUpdateWrapper);

                });
                reStatistics(deviceId, REAGENT_USE, barcodes.size());
            }
        }
    }
}
